package controller;


import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import entity.Students;
import service.StudentsService;
import service.impl.StudentsServiceimpl;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/StudentsController")
public class StudentsController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession(true);
        String op = req.getParameter("op");
        PrintWriter out=resp.getWriter();

        if (op.equals("sccx")) {

            // 获取前端传递的参数
            String xh = req.getParameter("xh");
            String name = req.getParameter("name");
            String pageStr = req.getParameter("page");
            int page = StringUtils.isNullOrEmpty(pageStr) ? 0 : Integer.parseInt(pageStr);
            int pageSize = 4; // 每页2条记录
    
            StudentsService stu = new StudentsServiceimpl();
            List<Students> list = null;
            int totalCount = 0;
    
            try {
                // 查询总记录数
                totalCount = stu.getTotalCount(xh, name);
                // 计算总页数(向上取整)
                int totalPages = (totalCount + pageSize - 1) / pageSize;
                // 确保页码在有效范围内
                page = Math.max(0, Math.min(page, totalPages - 1));
                
                // 查询当前页数据
                list = stu.cx(xh, name, page, pageSize);
    
                // 构建返回结果
                Map<String, Object> result = new HashMap<>();
                result.put("list", list);
                result.put("page", page);
                result.put("totalPages", totalPages);
                result.put("totalCount", totalCount);
                out.write(JSON.toJSONString(result));
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库操作失败");
            }
        }else if(op.equals("update")){
            String idStr = req.getParameter("id");
            String studentNumber = req.getParameter("student_number");
            String name = req.getParameter("name");
            String gender = req.getParameter("gender");

            // 参数验证
            if(idStr == null || studentNumber == null || name == null || gender == null) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "缺少必要参数");
                return;
            }

            try {
                int id = Integer.parseInt(idStr);
                StudentsService stus = new StudentsServiceimpl();
                try {
                    stus.modify(studentNumber, name, gender,id); // 修改方法使用数字ID
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                resp.getWriter().write("success");
            } catch (NumberFormatException e) {
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的ID格式");
            } catch (SQLException | NamingException e) {
                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库操作失败");
                e.printStackTrace();
            }
        }else if(op.equals("add")){
            String id=req.getParameter("student_number");
            String name=req.getParameter("name");
            String gender=req.getParameter("gender");
            StudentsService stus = new StudentsServiceimpl();
            try {
                try {
                    stus.append(id,name,gender);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }else if(op.equals("delete")){
            String id=req.getParameter("student_number");
            StudentsService stus = new StudentsServiceimpl();
            try {
                try {
                    stus.delete(Integer.parseInt(id));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }else if(op.equals("query")){
            StudentsService stus = new StudentsServiceimpl();
            List<Students> list=null;
            try {
                list=stus.cxcw();
            } catch (SQLException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            out.write(JSON.toJSONString(list));
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        doGet(req, resp);
    }

}
